package manager;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.DBConnector;

import com.sun.org.apache.bcel.internal.classfile.Attribute;

/**
 * Servlet implementation class AddNewStyleSheet
 */
public class AddNewStyleSheet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddNewStyleSheet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getSession(false).getAttribute("username").toString();
		if (request.getSession(false) == null || request.getSession(false).getAttribute("username") == null){
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Please login first");
			return;
		}
			
		String contentType = request.getContentType();              
        if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
            DataInputStream in = new DataInputStream(request.getInputStream());
	        //we are taking the length of Content type data
            int formDataLength = request.getContentLength();
            byte dataBytes[] = new byte[formDataLength];
            int byteRead = 0;
            int totalBytesRead = 0;
            
            //this loop converting the uploaded file into byte code
            while (totalBytesRead < formDataLength) {
            	byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                totalBytesRead += byteRead;  
            }
	        String file = new String(dataBytes);
	         //for saving the file name
	        String saveFile = file.substring(file.indexOf("filename=\"") + 10);
	        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
	        saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
            int lastIndex = contentType.lastIndexOf("=");
            String boundary = contentType.substring(lastIndex + 1,
    		contentType.length());
            int pos;
            //extracting the index of file 
            pos = file.indexOf("filename=\"");
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            int boundaryLocation = file.indexOf(boundary, pos) - 4;
            int startPos = ((file.substring(0, pos)).getBytes()).length;
            int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
	        // creating a new file with the same name and writing the content in new file
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            os.write(dataBytes, startPos, (endPos - startPos));
            os.flush();
            os.close();
            if (saveFile == null || saveFile.equals("")){
    			response.sendError(HttpServletResponse.SC_FORBIDDEN, "File can not be empty");
            	return;
            }
 
           

            try {
            	
            	DBConnector dbConn = new DBConnector();
				PreparedStatement stmnt = dbConn.getConnection().prepareStatement(
						"insert into user_stylesheets " +
						"values (?, ?, ?); ");
			
				stmnt.setString(1, username);
				stmnt.setString(2, saveFile);
				stmnt.setBinaryStream(3, new ByteArrayInputStream(os.toByteArray()));
				stmnt.execute();
            
				response.sendRedirect("/custom_stylesheet.jsp");
            } catch (SQLException e) {
				response.sendError(HttpServletResponse.SC_FORBIDDEN, "You can have only one stylesheet named " +
						saveFile + " try Deleteing first");
				e.printStackTrace();
				return;
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            
        }
	}

}
